#include "loadingdialog.h"

#include <QApplication>
#include <QPainterPath>
#include <QPainter>
#include <QStyleOption>
#include <QTimer>
#include <QIcon>
#include <QKeyEvent>
#include <QDateTime>

LoadingDialog::LoadingDialog(QWidget *parent)
    : QWidget(parent)
{
    setAttribute(Qt::WA_TranslucentBackground);
    setContentsMargins(0,0,0,0);
    //setProperty("useStyleWindowManager", false);

    m_layoutMain = new QHBoxLayout();
    m_layoutMain->setContentsMargins(0,0,0,0);
    m_layoutMain->setSpacing(0);
    m_layoutMain->setAlignment(Qt::AlignCenter);

    m_labelLoading = new QLabel();
    m_labelLoading->setProperty("useIconHighlightEffect", 0x2);
    m_layoutMain->addWidget(m_labelLoading);

    m_timerLoading = new QTimer(this);
    connect(m_timerLoading, SIGNAL(timeout()), this, SLOT(onLoading()));
    m_timerLoading->setInterval(100);
    m_timerLoading->start();
    m_lluInitTick = QDateTime::currentDateTime().toMSecsSinceEpoch();

    this->setLayout(m_layoutMain);
}

LoadingDialog::~LoadingDialog()
{
    if (m_timerLoading) {
        if(m_timerLoading->isActive())
            m_timerLoading->stop();
    }
}

void LoadingDialog::paintEvent(QPaintEvent *event)
{
    QPainterPath path;
    QPainter painter(this);

    path.addRect(this->rect());
    path.setFillRule(Qt::WindingFill);
    painter.setOpacity(0);
    painter.setBrush(Qt::NoBrush);
    painter.setPen(Qt::NoPen);
    painter.drawPath(path);
    QWidget::paintEvent(event);
}

void LoadingDialog::onLoading()
{
    QString strFrame = QString("ukui-loading-%1-symbolic").arg(m_nCurTick);
    QIcon iconFrame = QIcon::fromTheme(strFrame);
    if (!iconFrame.isNull()) {
        m_labelLoading->setPixmap(iconFrame.pixmap(40,40));
    }
    m_nCurTick ++;
    if (m_nCurTick>7) {
        m_nCurTick = 0;
    }
}

void LoadingDialog::closeEvent(QCloseEvent *event)
{
    if (m_timerLoading) {
        if(m_timerLoading->isActive())
            m_timerLoading->stop();
    }
}

void LoadingDialog::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Escape){
        if (QDateTime::currentDateTime().toMSecsSinceEpoch()-m_lluInitTick>=10*1000){
            //this->close();
        }
    } else {
        QWidget::keyPressEvent(event);
    }
}

void LoadingDialog::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
}

void LoadingDialog::mouseMoveEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
}
